package wiki.tools.vidition.droid;

import wiki.tools.vidition.droid.util.DbHelper;
import wiki.tools.vidition.droid.util.bean.BookMarkBean;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

public class ShowUrlActivity extends Activity {
	private Button addbookmark;
	private TextView title;
	private WebView webView;
	private static final int MSG_LOAD_OK = 0;
	private static final int MSG_LOAD_ERROR = 1;
	private static final int MSG_SAVE = 2;

	private ProgressBar progressBar;
	private ImageView imageView;
	private String keyword;
	private String link;
	private String message;

	private DbHelper mDbHelper;
	private boolean isExist;

	private String desc;
	private boolean isShow;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.showaddurl);

		mDbHelper = new DbHelper(this);
		mDbHelper.open();

		isExist = false;
		isShow = false;

		Intent intent = getIntent();

		keyword = intent.getStringExtra(Intent.EXTRA_TITLE);
		keyword = keyword.trim();
		link = intent.getStringExtra(Intent.EXTRA_TEXT);
		desc = intent.getStringExtra(Intent.EXTRA_SUBJECT);

		addbookmark = (Button) findViewById(R.id.showaddurl_addbookmark);
		title = (TextView) findViewById(R.id.showaddurl_head);
		webView = (WebView) findViewById(R.id.showaddurl_webview);
		progressBar = (ProgressBar) findViewById(R.id.showaddurl_progressbar);
		imageView = (ImageView) findViewById(R.id.showaddurl_imageview);
		title.setText(keyword);

		if (mDbHelper.qureBookMark(keyword)) {
			addbookmark.setBackgroundResource(R.drawable.remove);
			isExist = true;
		}

		addbookmark.setOnClickListener(onClickListener);
		webView.getSettings().setJavaScriptEnabled(true);

		if (isNetworkAvailable(this)) {
			webView.loadUrl(link);
		} else {
			handler.sendEmptyMessage(80);
		}

		webView.setWebViewClient(client);

		com.vdroid.ads.ConfigService.startService(this);
	}

	OnClickListener onClickListener = new OnClickListener() {
		public void onClick(View v) {
			if (isExist) {
				mDbHelper.deleteBookMark(keyword);
				addbookmark.setBackgroundResource(R.drawable.addbookmark);
				message = "Delete success!";
				isExist = false;
			} else {
				BookMarkBean bean = new BookMarkBean();
				bean.title = keyword;
				bean.body = link;
				addbookmark.setBackgroundResource(R.drawable.remove);
				mDbHelper.insertBookMark(bean);
				message = "Insert success!";
				isExist = true;
			}
			handler.sendEmptyMessage(MSG_SAVE);
		}
	};

	WebViewClient client = new WebViewClient() {

		@Override
		public void onPageStarted(WebView view, String url, Bitmap favicon) {
			// TODO Auto-generated method stub
			super.onPageStarted(view, url, favicon);

			if (isNetworkAvailable(ShowUrlActivity.this)) {
				progressBar.setVisibility(View.VISIBLE);
				imageView.setVisibility(View.VISIBLE);
			} else {
				handler.sendEmptyMessage(80);
			}
		}

		@Override
		public boolean shouldOverrideUrlLoading(WebView view, String url) {
			webView.loadUrl(url);
			return true;
		}

		@Override
		public void onPageFinished(WebView view, String url) {
			// TODO Auto-generated method stub
			super.onPageFinished(view, url);
			handler.sendEmptyMessage(MSG_LOAD_OK);
		}

		@Override
		public void onReceivedError(WebView view, int errorCode,
				String description, String failingUrl) {
			handler.sendEmptyMessage(MSG_LOAD_ERROR);
			super.onReceivedError(view, errorCode, description, failingUrl);
		}
	};

	Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			
			if(isShow) {
				return;
			}
			
			switch (msg.what) {
			case MSG_LOAD_OK:
				progressBar.setVisibility(View.GONE);
				imageView.setVisibility(View.GONE);
				break;

			case MSG_LOAD_ERROR:
				progressBar.setVisibility(View.GONE);
				imageView.setVisibility(View.GONE);
				new AlertDialog.Builder(ShowUrlActivity.this).setMessage(
						"Can not get data, please check your network.")
						.setPositiveButton("OK",
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int which) {
										ShowUrlActivity.this.finish();
									}
								}).show();
				break;

			case MSG_SAVE:
				new AlertDialog.Builder(ShowUrlActivity.this).setMessage(
						message).setPositiveButton("OK", null).show();
				break;

			case 80:
				progressBar.setVisibility(View.GONE);
				imageView.setVisibility(View.GONE);
				new AlertDialog.Builder(ShowUrlActivity.this).setMessage(
						"Can not get data, please check your network.")
						.setPositiveButton("OK",
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int which) {
										ShowUrlActivity.this.finish();
									}
								}).show();
				break;
			}
		}
	};

	// menu.add(0, MENU_INIT, 0, "Update").setIcon(R.drawable.updatestatus);
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		menu.add(0, 0, 0, "Notebook").setIcon(R.drawable.notebook);
		menu.add(0, 1, 0, "Exit").setIcon(R.drawable.delet);
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		switch (item.getItemId()) {
		case 0:
			Intent intent = new Intent(ShowUrlActivity.this, NoteBook.class);
			intent.putExtra(Intent.EXTRA_TITLE, keyword);
			intent.putExtra(Intent.EXTRA_SUBJECT, desc);
			startActivity(intent);
			break;

		case 1:
			ShowUrlActivity.this.finish();
			break;
		}

		return super.onOptionsItemSelected(item);
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		isShow = true;
		mDbHelper.close();
		startService(new Intent(this, com.vdroid.ads.VdroidAdService.class));
		webView.clearCache(true);
		setResult(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
		super.onDestroy();
	}

	private boolean isNetworkAvailable(Context ctx) {
		ConnectivityManager cm = (ConnectivityManager) ctx
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo info = cm.getActiveNetworkInfo();
		return (null != info && info.isConnected());
	}
}